package com.easybacklog.client.webservices.github;

import java.util.HashMap;

import com.easybacklog.client.EasyBacklogGlobalVariables;
import com.easybacklog.client.cucumberfeatures.BacklogFeaturesList;
import com.easybacklog.client.cucumberfeatures.ProductBacklogView;
import com.easybacklog.client.model.Project;
import com.easybacklog.client.model.ProjectFeature;
import com.easybacklog.client.webservices.GetFileContent;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Communicates via REST Web Service
 * 
 */
public class RequestGithubListFeatures {

	// http://livesourceagile.com:8080/LiveSourceWebServices/ListGithubFeatureFilesService
	// ?projectName=TravelLog
	// &username=allineo
	// &featuresPath=features

	private static String url = "http://livesourceagile.com:8080/LiveSourceWebServices/ListGithubFeatureFilesService";

	public static void getJsonpRequest(final Project project) {

		// String username = EncryptText.decrypt(GetCookies.getUsername(project
		// .getProjectID()));
		String username = null;

		// String password =
		// EncryptText.decrypt(GetCookies.getPassword(project.getProjectID()));
		String password = null;

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		jsonp.setTimeout(50000);

		String urlList = url + "?projectName="
		// + project.getGithubProjectName()
		// + "&username=" + project.getGithubUserName() + "&featuresPath="
				+ EasyBacklogGlobalVariables.featuresPath;

		jsonp.requestObject(urlList, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
				Window.alert(throwable.toString());
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject objFeed = new JSONObject(feed);

				HashMap<String, ProjectFeature> files = new HashMap<String, ProjectFeature>();

				for (int i = 0; i < objFeed.size(); i++) {

					JSONObject entry = (JSONObject) objFeed.get(i + "");

					ProjectFeature projectEntry = ConvertGithubToProjectFeature
							.convertJsonp(entry);

					files.put(projectEntry.toString(), projectEntry);

					new GetFileContent(projectEntry,
							EasyBacklogGlobalVariables.currentProject);
				}

				EasyBacklogGlobalVariables.projectFeatures = files;

				ProductBacklogView.vpProjectBacklog.clear();

				ProductBacklogView.vpProjectBacklog
						.add(new BacklogFeaturesList());
			}
		});
	}
}
